package com.kafka.producer;


import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 同步发送
 *
 */

public class SyncProducer {

    public static void main(String[] args) {
        Properties props = new Properties();


        // Kafka 服务端的主机名和端口号
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.100.125:9092");

        // key 序列化
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        // value 序列化
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer(props);

        for (int i = 0; i < 50; i++) {

            // 指定相同的key 会发送到相同的分区partition
            Future<RecordMetadata> first = producer.send(new ProducerRecord<String, String>("first",

                    "hello world-" + i));

            try {

                RecordMetadata recordMetadata = first.get();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

        }

        producer.close();
    }
}
